<?php

/**
 * @Description    用户模型
 * @Author         zhaojiping
 * @Copyright      山东艾思软件科技有限公司(https://www.aisisofit.cn)
 * @Date           2022/1/20
 * @CreateBy       VS Code
 */

namespace app\core\model;

use think\facade\Db;

class CoreUser extends \app\common\model\CommonModel {
    protected $readonly = ['id', 'create_time', 'update_time'];
    protected $fields   = 'id, sn, username, nickname, title_id, avatar, email, mobile, usable, is_manager, role_id, department_id,create_time';
    protected $order    = 'department_id, is_manager desc, id';            // 排序字段

    public $with = ['withBelongsTo'];

    /**
     * 分类关联
     */
    public function withBelongsTo() {
        return $this->belongsTo('CoreDepartment', 'department_id', 'id')->bind(['department_name' => 'name']);
    }

    public static function onAfterRead($row) {
        parent::onAfterRead($row);
        // 获取岗位名称
        $row['title_name'] = '';
        if (isset($row->title_id) && $row->title_id > 0) {
            $row['title_name'] = Db::name('coreTitle')->where(['id' => $row['title_id']])->value('name');
        }
    }

    public static function onBeforeWrite($row) {
        parent::onBeforeWrite($row);
    }
    /**
     * 添加前的操作
     */
    public static function onBeforeInsert($row) {
        parent::onBeforeInsert($row);

        if (empty($row->avatar))  $row->avatar = '/static/images/avatar.png';
        $default_password = cache('config')['default_password'];
        $salt = rand_str(6);
        $row->salt = $salt;
        if (isset($row->password) && strlen($row->password) >= $default_password)
            $row->password = md5($row->password . $salt);
        else
            $row->password = md5($default_password . $salt);
        $row->token = rand_str(18);

        // 生成员工编号
        $row->sn = self::createSn();

        cache('core_department_all', null);
    }

    /**
     * 更新前的操作
     */
    public static function onBeforeUpdate($row) {
        parent::onBeforeUpdate($row);

        if (!empty($row->password)) {
            $salt = rand_str(6);
            $row->salt = $salt;
            if (isset($row->password) && strlen($row->password) >= cache('config')['password_length'])
                $row->password = md5($row->password . $salt);
            else
                json_return(0, '密码需要 ' . cache('config')['password_length'] . ' 位以上');
        }

        cache('core_department_all', null);
    }

    /**
     * 删除前的操作
     */
    public static function onBeforeDelete($row) {
        parent::onBeforeDelete($row);

        if ($row['id'] == 1) json_return(0, '系统管理员不能删除');

        cache('core_department_all', null);
    }

    /**
     * 生成用户编号
     */
    public static function createSn() {
        $user_sn_rule = cache('config')['user_sn_rule'];
        $sn = '';
        if ($user_sn_rule == 1)
            $sn = self::where('sn >= 100000001 and sn <= 999999999')->max('sn'); // 有年份, 获取最大编号
        else
            $sn = self::where('sn >= 1 and sn <= 99999')->max('sn'); // 无年份, 获取最大编号

        $sn = $sn ? ($sn + 1) : '1'; // 如果没有:以1赋值, 如果有:+1
        $sn = substr($sn, -5); // 取出后五位
        $sn = str_pad($sn, 5, '0', STR_PAD_LEFT); // 在第一次时, 补齐五位防止不够
        if (cache('config')['user_sn_rule'] == 1) $sn = date('Y') . $sn;  // 根据设置加上年份

        return $sn;
    }

    /**
     * 用户登录
     */
    public static function login($username, $password) {
        /* 获取用户数据 */
        $user = self::where('username', $username)->field(true)->find();
        // echo self::getLastSql();
        if (!$user)
            json_return(0, '登录名或密码错误.');

        // 验证是否禁用, 超级管理员不能禁用
        if ($user['username'] != 'admin') {
            if ($user['usable'] != 1) json_return(0, '登录被禁用, 请与管理员联系.');
            // 验证用户的角色是否禁用
            $usable = Db::name('CoreRole')->where(['id' => $user['role_id']])->value('usable');
            if ($usable === 0) json_return(0, '登录被禁用, 请与管理员联系!');
        }

        // 验证用户密码
        if (md5($password . $user['salt']) === $user['password']) {
            unset($user['password']);
            unset($user['salt']);
            $user['department_name'] = Db::name('CoreDepartment')->where(['id' => $user['department_id']])->value('name');
            // 登录成功，返回用户信息
            json_return(1, '登录成功', $user);
        } else {
            json_return(0, '登录名或密码错误!');
        }
    }
}
